<?php

namespace backend\models;

use Yii;
use common\models\UserInfo;

/**
 * This is the model class for table "admin_info".
 *
 * @property integer $id
 * @property string $username
 * @property string $nickname
 * @property string $tel
 * @property string $email
 * @property string $password_hash
 * @property string $auth_key
 * @property integer $confirmed_at
 * @property string $registration_ip
 * @property integer $created_at
 * @property string $lastlogin_ip
 * @property integer $lastlogin_at
 * @property integer $updated_at
 * @property string $status
 * @property string $user_type
 * @property integer $blocked_at
 */
class AdminInfo extends \yii\db\ActiveRecord
{
    public $password;
    public $verifyPassword;
  //  public $address;
    /**
     * @inheritdoc
     */
    const STATUS_ACTIVE = "1";
    const STATUS_DELETED = "2";
    const STATUS_BLOCKED = "3";
    
    const DEFAULT_PASSWORD = '111111';
    
    public static function tableName()
    {
        return 'admin_info';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username'], 'required'],
            [['confirmed_at', 'created_at', 'lastlogin_at', 'updated_at', 'blocked_at', 'user_id'], 'integer'],
            [['username', 'nickname'], 'string', 'max' => 100, 'min' => 3],
           
            [['tel'], 'string', 'max' => 18],
            [['email'], 'string', 'max' => 255],
            [['password'], 'string', 'max' => 60,'min' =>6],
            [['auth_key'], 'string', 'max' => 32],
            [['registration_ip', 'lastlogin_ip'], 'string', 'max' => 45],
            
            [['user_type'], 'string', 'max' => 1],
            [['username'], 'unique' ],
            [['email'], 'unique'],
            [['tel'], 'unique'],
            
            ['email','email'],
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED, self::STATUS_BLOCKED]],
            
            'verifyPasswordTrim' => ['verifyPassword', 'filter', 'filter' => 'trim'],
           // 'verifyPasswordRequired' => ['verifyPassword', 'required','message'=>'{attribute}不能为空'],
            'verifyPasswordCompare' => ['verifyPassword', 'compare', 'compareAttribute'=>'password', 'message'=>'确认密码不一致，请再输入'],
            

            
            
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => Yii::t('user','Username'),
            'nickname' => Yii::t('user','Nickname'),
            'tel' => Yii::t('user','Tel'),
            'email' => Yii::t('user','Email'),
            'password_hash' => 'Password Hash',
            'password' => Yii::t('user','Password'),
            'verifyPassword' => Yii::t('user','VerifyPassword'),
            'auth_key' => 'Auth Key',
            
            'registration_ip' => Yii::t('user','Registration Ip'),
            'created_at' => Yii::t('user','Created At'),
            'lastlogin_ip' => Yii::t('user','Lastlogin Ip'),
            'lastlogin_at' => Yii::t('user','Lastlogin At'),
            'updated_at' => Yii::t('user','Updated At'),
            'status' => Yii::t('user','Status'),
            'user_type' => Yii::t('user','User Type'),
            'blocked_at' => Yii::t('user','Blocked At'),
            'dep_id' => Yii::t('app','DepId'),
            'user_id'=>Yii::t('app','User ID')
        ];
    }
    public function getUserInfo(){
    	return $this->hasOne(UserInfo::className(), ['id'=>'user_id']);
    }
    public function createadmin()
    {
    	$this->password_hash = Yii::$app->security->generatePasswordHash($this->password ==null ? self::DEFAULT_PASSWORD : $this->password);
    	$this->registration_ip = Yii::$app->request->userIP;
    	$this->auth_key = Yii::$app->security->generateRandomString();
    	$this->created_at = time();
    	$this->updated_at = time();
    	
    	if(!$this->user_id) $this->user_type = '1';
    	else $this->user_type ='5';
    	if($this->save())
    	{
    		return true;
    	}
    	return false;
    	
    }
    public function update_password($password)
    {
    	return Yii::$app->security->generatePasswordHash($this->password);
    	
    }
    public function scenarios()
    {
    	$scenarios = parent::scenarios();
		$scenarios['update_info'] = ['nickname','password','verifyPassword'];
		return $scenarios;
    }
    public static function getUsernameById($uid)
    {
    	$model = self::findOne(['id'=>$uid]);
    	if($model != null){
    		return $model;
    	}
    }
    public static function getUIdByUsername($username)
    {
    	$model = self::findOne(['username'=>$username]);
    	if($model != null){
    		return $model;
    	}
    }
    
    /**admin绑定user_id
     * 1:1
     * */
	public static function unique_admin_user($admin_id,$user_id){
		if($user_id=='0')
			return true;//平台管理员不验证
		$condition = "user_id ={$user_id}";//新增
		if($admin_id) $condition .=" AND id <> {$admin_id}";//修改
		
		$admin_user = AdminInfo::find()->where($condition)->one();
		$count = count($admin_user);
		if($count != 0) return $admin_user;
		elseif($count == 0) return true;	
	}
	public static function check_create($action){
	    if($action == 'create' &&(\Yii::$app->user->can('yys-create') || Yii::$app->user->identity->user_type ==1)){
	        return true;
	    }else{
	        $user_id=Yii::$app->user->identity->user_id;
	        $sql="select id from admin_info where user_id=:user_id";
	        $param=array(":user_id"=>$user_id);
	        $AdminList=AdminInfo::findBySql($sql,$param)->asArray()->all();
	        $hasCreate=false;
	        for($i=0;$i<count($AdminList);$i++){
	            $check=Yii::$app->authManager->checkAccess($AdminList[$i]['id'] ,"yys-create");
	            if($check){
	                $hasCreate= true;
	                break;
	            }
	        }
	        
	    }
	    if($hasCreate){
	        return true;
	    }
		return false;
	}
	/**
	 * 根据运营商判断是否有新增权限
	 * @param unknown $action
	 * @return boolean
	 */
	public static  function check_opcreate($action){
	    
	    if($action == 'create' &&(\Yii::$app->user->can('yys-create') || Yii::$app->user->identity->user_type ==1)){
	        return true;
	    }else{
	        $user_id=Yii::$app->user->identity->user_id;
	        $sql="select id from admin_info where user_id=:user_id";
	        $param=array(":user_id"=>$user_id);
	        $AdminList=AdminInfo::findBySql($sql,$param)->asArray()->all();
	        $hasCreate=false;
	        for($i=0;$i<count($AdminList);$i++){
	            $check=Yii::$app->authManager->checkAccess( $AdminList[$i]['id'] , "yys_create");
	            if($check){
	                $hasCreate= true;
	                break;
	            }
	        }
	        if($hasCreate){
	            return true;
	        }
	    }
	    return false;
	}
	//判断后台管理员是否有操作权限【运营商范围内】根据编辑人
	public static function check_user_id($login_id,$admin_id,$permission='view'){
		//登录的用户类别
		$login_info = AdminInfo::findOne(['id'=>$login_id]);
		
		if($login_info['user_type']==1){
			return true;
		}elseif($login_info['user_type']!=1){//非后台管理员
			$admin_ids = self::get_all_admin_by_operator($login_id);//可编辑的
			if(!is_array($admin_ids))	$admin_ids = explode(',', $admin_ids);
			if($permission=='view' && \Yii::$app->user->can('yys-view-platform')){
				return true;//查看平台的
			}elseif($permission=='edit' && in_array($admin_id, $admin_ids) && \Yii::$app->user->can('yys-edit-all'))
				return true;//编辑运营商的
			elseif($permission=='view' && in_array($admin_id, $admin_ids) && \Yii::$app->user->can('yys-view-all'))
				return true;//查看运营商的
			elseif( $permission=='edit' && $login_info['id'] == $admin_id && \Yii::$app->user->can('yys-edit-own'))
				return true;//编辑自己的
			elseif( $permission=='view' && $login_info['id'] == $admin_id && \Yii::$app->user->can('yys-view-own'))		
				return true;//查看自己的
		}
		
		return false;
	}
	//判断后台管理员是否有操作权限【运营商范围内】根据编辑人   碎月 
	public static function check_hasoperator($login_id,$admin_id,$permission='view'){
	    //设计师 传递的是uid
	    if($permission=="designer"){
	        
	    }
	    $login_info = AdminInfo::findOne(['id'=>$login_id]);
	    //用于edit
	    $operation=false;
	    $admin_info= AdminInfo::findOne(['id'=>$admin_id]);
	    $admin_userid=intval($admin_info['user_id']);
	    $login_userid=intval($login_info['user_id']);
	    if($admin_userid==$login_userid){
	        $operation=true;
	    }
	    //登录的用户类别
	  
	    if($login_info['user_type']==1){//管理员 可以操作任何
	        return true;
	    }elseif($login_info['user_type']!=1){//非后台管理员
	        $admin_ids = self::get_all_admin_by_operator($login_id);//可编辑的
	        if(!is_array($admin_ids))
	        $admin_ids = explode(',', $admin_ids);
	        if($permission=='view' && \Yii::$app->user->can('yys-view-platform')){
	            return true;//查看平台的
	            //elseif($permission=='edit' && in_array($admin_id, $admin_ids) && \Yii::$app->user->can('yys-edit-all'))
	           // return true;//编辑运营商的 
	        } elseif($permission=='view' && in_array($admin_id, $admin_ids) && \Yii::$app->user->can('yys-view-all'))
	        return true;//查看运营商的
	        elseif($permission=='edit'&& \Yii::$app->user->can('yys-edit-own')&& \Yii::$app->user->can('yys-edit-all')&&$operation)
	        return true;//编辑自己的
	        elseif( $permission=='view' && $login_info['id'] == $admin_id && \Yii::$app->user->can('yys-view-own'))
	        return true;//查看自己的
	    }
	    //判断admin_id 和 login_id是否为同一个运营商
	   
	    return false;
	    
	}
	 
	/**
	 * 判断当前运营商是否可以查看   不同运营商   上级可以查看下级，下级不可以查看上级
	 * @param   $login_id  可以不用了
	 * @param   $admin_id
	 * @param string $permission
	 * @return boolean
	 */
	public static function check_lookoperator($login_id,$admin_id,$permission='view'){
	    //登录的用户类别
	    $login_info = AdminInfo::findOne(['id'=>$login_id]);
	    if($login_info['user_type']==1){//管理员 可以操作任何
	        return true;
	    }elseif($login_info['user_type']!=1){//非后台管理员
	        $admin_ids = self::get_all_admin_by_operator($login_id);//可编辑的
	        if(!is_array($admin_ids))
	            $admin_ids = explode(',', $admin_ids);
	            if($permission=='view' && \Yii::$app->user->can('yys-view-platform')){
	                return true;//查看平台的
	            }elseif($permission=='edit' && in_array($admin_id, $admin_ids) && \Yii::$app->user->can('yys-edit-all'))
	            return true;//编辑运营商的
	            elseif($permission=='view' && in_array($admin_id, $admin_ids) && \Yii::$app->user->can('yys-view-all'))
	            return true;//查看运营商的
	            elseif( $permission=='edit' && $login_info['id'] == $admin_id && \Yii::$app->user->can('yys-edit-own'))
	            return true;//编辑自己的
	            elseif( $permission=='view' && $login_info['id'] == $admin_id && \Yii::$app->user->can('yys-view-own'))
	            return true;//查看自己的
	    }
	    //判断admin_id 和 login_id是否为同一个运营商
	    $admin_info= AdminInfo::findOne(['id'=>$admin_id]);
	    $admin_userid=intval($admin_info['user_id']);
	    $login_userid=intval($login_info['user_id']);
	    if($admin_userid==$login_userid){
	        return true;
	    }else{
	        $admin_operator=OperatorRelation::findBySql("select parent from prf_operator_relation where uid=:uid  and useing=1",array(":uid"=>$admin_userid))->asArray()->one();
	        $parentId=intval($admin_operator['parent']);
	        if($parentId==$login_userid){
	            return true;
	        }else{
	            return false;
	        }
	    }
	    return false;
	}
	
	//有登录admin_id获得同一运营商下所有admin
	public static function get_all_admin_by_operator($admin_id){
	    //查询同一个运营商
		$info = AdminInfo::findOne(['id'=>$admin_id]);
		$all = AdminInfo::findAll(['user_id'=>$info['user_id']]);
		$ids = array();
		foreach ($all as $val){
			if($val['id'])
				array_push($ids, $val['id']);
		}
		//查询 当前运营商的下级
		$sql="SELECT uid FROM prf_operator_relation WHERE parent=:parent";
		$param=array(":parent"=>$info['user_id']);
		$childOperatorList=OperatorRelation::findBySql($sql,$param)->asArray()->all();
		for($i=0;$i<count($childOperatorList);$i++){
		    $uid=$childOperatorList[$i]['uid'];
		    $all = AdminInfo::findAll(['user_id'=>$uid]);
		    foreach ($all as $val){
		        if($val['id'])
		            array_push($ids, $val['id']);
		    }
		}
		return implode(',', $ids);
	}
	//销售订单修改的权限
	public static function check_sale($model,$login_id,$permission = 'update'){
	    //判断当前运营商所管理的所有城市
		$login_info = AdminInfo::findOne(['id'=>$login_id]);
		$user_id=Yii::$app->user->identity->user_id;//判断当前运营商的所有城市
		$user_type=intval(Yii::$app->user->identity->user_type);
		if($user_type==1){//后台管理员可修改任何订单
		    return true;
		}
		$address=$model->address;
		$_arr = explode(' ', $address);
		$ifhascity=OperatorRelation::ifhascity();
		$ifhaszxsCountry=OperatorRelation::ifhaszxsCountry();
		$ifhascountry=OperatorRelation::ifhascountry();
		$operation=false;
		if($ifhascity){
		    $city=$_arr[0];
		    $cityList=OperatorRelation::getCityNameByIdNparent();
		    if(count($cityList>0)){
		        if(in_array($city, $cityList)){
		            $operation=true;
		        }
		    }
		}
		if($ifhaszxsCountry||$ifhascountry){
		    $countryList=OperatorRelation::getcountryNameByIdNparent();
		    $country="";
		    if($ifhaszxsCountry){
		        if(count($_arr)>=2){
		            $country="'".$_arr[0]." ".$_arr[1]."'";
		        }
		    }else{
		        if(count($_arr)>=3){
		            $country="'".$_arr[0]." ".$_arr[1]." ".$_arr[2]."'";
		        }
		    }
		    if(in_array($country, $countryList)){
		        $operation=true;
		    }
		}
		
		if($permission == 'update'){//更新
			if(\Yii::$app->user->can('paytrade-update')){
				if($login_info['user_type'] == 1)//平台管理员
					return true;
					 elseif($operation)
					 return true;
				else 
					return false;
			}else{
				return false;
			}
		}
		if($permission == 'audit'){//审核
			if(\Yii::$app->user->can('paytrade-audit')){
				if($login_info['user_type'] == 1)//平台管理员
					return true;
					elseif($operation)
					return true;
				else
					return false;
			}else{
				return false;
			}
		}
	}

	public function getDesignerInfo()
	{
		return $this->hasOne(SysUserDesigner::className(),['uid'=>'id']);
	}
}












